package com.xidian.zhiancloud.util.constants;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.*;


public class StringRandoms {

	//使用到Algerian字体，系统里没有的话需要安装字体，字体只显示大写，去掉了1,0,i,o几个容易混淆的字符
	public static final String VERIFY_CODES = "1234567890";

	/**
	 * 使用系统默认字符源生成验证码
	 * @param verifySize    验证码长度
	 * @return
	 */
	public static String generateVerifyCode(int verifySize){
		return generateVerifyCode(verifySize, VERIFY_CODES);
	}

	/**
	 * 使用指定源生成验证码
	 * @param verifySize    验证码长度
	 * @param sources   验证码字符源
	 * @return
	 */
	public static String generateVerifyCode(int verifySize, String sources){
		if(sources == null || sources.length() == 0){
			sources = VERIFY_CODES;
		}
		int codesLen = sources.length();
		Random rand = new Random(System.currentTimeMillis());
		StringBuilder verifyCode = new StringBuilder(verifySize);
		for(int i = 0; i < verifySize; i++){
			verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
		}
		return verifyCode.toString();
	}

	public static void main(String[] args) {
		System.out.println(generateVerifyCode(4));
	}

	/**
	 * 随机获取当前年月日+随机的七位数字	lining
	 * 
	 * 大家根据自己的业务需求判断，如果需要保证这个随机数字的唯一性
	 * 每次调用的时候，先判断，比如新增的时候，先判断这个随机数是不是存在
	 * 如果存在就重新获取，如果不存在的话，直接调用就OK
	 */
	public static String randowCount(){
		String string = "";
		Random rd = new Random();
		for (int i = 0; i < 7; i++) {
			string = string+rd.nextInt(9);
		}
		if ((Calendar.getInstance().get(Calendar.MONTH)+1)<10) {
			if(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)<10){
				string = Calendar.getInstance().get(Calendar.YEAR)+"0"+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+"0"+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;	
			}else{
				string = Calendar.getInstance().get(Calendar.YEAR)+"0"+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+""+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;
			}
		}else{
			if(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)<10){
				string = Calendar.getInstance().get(Calendar.YEAR)+""+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+"0"+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;	
			}else{
				string = Calendar.getInstance().get(Calendar.YEAR)+""+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+""+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;
			}
		}
		return string;
	}
	//带参的获取当前的年月日+随机七位数
	public static String randowCounts(String string){
		Random rd = new Random();
		for (int i = 0; i < 7; i++) {
			string = string+rd.nextInt(9);
		}
		if ((Calendar.getInstance().get(Calendar.MONTH)+1)<10) {
			if(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)<10){
				string = Calendar.getInstance().get(Calendar.YEAR)+"0"+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+"0"+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;	
			}else{
				string = Calendar.getInstance().get(Calendar.YEAR)+"0"+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+""+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;
			}
		}else{
			if(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)<10){
				string = Calendar.getInstance().get(Calendar.YEAR)+""+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+"0"+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;	
			}else{
				string = Calendar.getInstance().get(Calendar.YEAR)+""+(Calendar.getInstance().get(Calendar.MONTH)+1)
						+""+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""+string;
			}
		}
		return string;
	}
	
	/**
	 * 将json对象转换成Map
	 * @param jsonObject
	 * @return Map对象
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> toMap(JSONObject jsonObject) {
		Map<String, String> result = new HashMap<String, String>();
		Iterator<String> iterator = jsonObject.keys();
		String key = null;
		String value = null;
		while (iterator.hasNext()) {
			key = iterator.next();
			try {
				value = jsonObject.getString(key);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			result.put(key, value);
		}
		return result;
	}

	// ////////////////////////////////
	public static String object2json(Object obj) throws Exception {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean || obj instanceof Short
				|| obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(string2json(obj.toString())).append("\"");
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			json.append(bean2json(obj));
		}
		return json.toString();
	}

	
	public static String bean2json(Object bean) throws Exception {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				String name = object2json(props[i].getName());
				String value = object2json(props[i].getReadMethod().invoke(bean));
				json.append(name);
				json.append(":");
				json.append(value);
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String list2json(List<?> list) throws Exception {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String array2json(Object[] array) throws Exception {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String map2json(Map<?, ?> map) throws Exception {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String set2json(Set<?> set) throws Exception {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String string2json(String s) {
		if (s == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}	

	/**
	 * @describe javabean转json，时间格式化“yyyy-MM-dd HH:mm:ss
	 * @param bean
	 * @return
	 */
	public static JSONObject fromatDate(Object bean){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());  
		
		return JSONObject.fromObject(bean, jsonConfig);
	}
	
	/**
	 * @describe javabean转json，自定义时间格式
	 * @param bean
	 * @param format 如“yyyy-MM-dd HH:mm:ss”
	 * @return
	 */
	public static JSONObject fromatDate(Object bean, String format){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor(format));  
		
		return JSONObject.fromObject(bean, jsonConfig);
	}
	
	/**
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static JSONArray fromatDateList(List list){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());  
		
		return JSONArray.fromObject(list, jsonConfig);
	}
	
	/**
	 * @param list
	 * @param format　如“yyyy-MM-dd HH:mm:ss”
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static JSONArray fromatDateList(List list, String format){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor(format));  
		
		return JSONArray.fromObject(list, jsonConfig);
	}
	
}
